package com.hunau.zshop.backend.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hunau.zshop.common.constant.PaginationConstant;
import com.hunau.zshop.pojo.AjaxObject;
import com.hunau.zshop.pojo.Customer;
import com.hunau.zshop.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/backend/customer")
public class CustomerController {

    @Autowired
    public CustomerService customerService;

    @RequestMapping("findAll")
    public String findAll(Integer pageNum, Model model){

        return "customerManager";
    }

    @RequestMapping("changeStatus")
    @ResponseBody
    public String changeStatus(Integer id,Integer isValid){
        try {
            //将用户状态关闭
            customerService.changeCustomer(id,isValid);
            return "OK";

        }catch (Exception e){
            System.out.println(e);
            return "FAIL";
        }

    }

    @RequestMapping("alterCustomer")
    @ResponseBody
    public String alterCustomer(@Valid Customer customer, BindingResult bindingResult) {
        System.out.println(customer);
        //判断传入的customer属性是否符合校验，不符合返回fail
        if(bindingResult.hasErrors()){
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for(ObjectError eror: allErrors){
                System.out.println(eror);
            }
            return "FAIL";

        }
        try {
            //修改customer的属性
            customerService.alterCustomer(customer);
            return "OK";
        } catch (Exception e) {
            System.out.println(e);
            return "FAIL";
        }
    }

    //查询customer
    @RequestMapping("search")
    @ResponseBody
    public AjaxObject searchCustomer(@RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                     Customer customer){
        System.out.println(customer);
        if (ObjectUtils.isEmpty(pageNum)){
            pageNum= PaginationConstant.PAGE_NUM;
        }
        //设置分页
        PageHelper.startPage( pageNum,PaginationConstant.PAGE_SIZE);
        //查找所有商品类型
        List<Customer> Customers = customerService.searchCustomer(customer);
        //将查询结果封装到PageInfo对象中
        PageInfo<Customer> pageInfo = new PageInfo<>(Customers);
        AjaxObject data = new AjaxObject();
        data.put("pageInfo",pageInfo).setSuccess();
        return data;
    }
}
